import { post } from "./request";

/**
 * 大文件分片上传
 * @param file 要上传的文件
 * @param onProgress 上传进度回调函数
 * @returns Promise<void>
 */
export const uploadBig = async (file: File, onProgress?: (progress: number) => void) => {
    try {
        // 初始化上传，获取文件ID
        const res = await post('/chunk/init')
        console.log("init size file", res)
        let hash = res.data
        if(!hash){
            console.error('获取文件ID失败')
            throw new Error('获取文件ID失败')
        }

        console.log("file size", file, file.size, file.type)

        // 分片大小：10MB
        let chunkSize = 1024 * 1024 * 10
        // let chunkSize = 1024 * 1024 * 10
        let chunkCount = Math.ceil(file.size / chunkSize)
        
        // 逐个上传分片
        for(let i = 0; i < chunkCount; i++){
            let chunk = file.slice(i * chunkSize, (i + 1) * chunkSize, file.type)
            console.log(`上传分片 ${i + 1}/${chunkCount}`, chunk)
            
            // 使用FormData格式上传分片
            const formData = new FormData()
            formData.append('chunk', chunk, `chunk_${i}`)
            // formData.append('fileId', hash)
            // formData.append('chunkIndex', i.toString())
            // formData.append('totalChunks', chunkCount.toString())
            
            let res = await post(`/chunk/upload?fileId=${hash}&chunkIndex=${i}&totalChunks=${chunkCount}`, formData)
            console.log("upload chunk", res)
            
            // 更新进度
            if (onProgress) {
                const progress = Math.round(((i + 1) / chunkCount) * 100)
                onProgress(progress)
            }
        }
        let res1 = await post(`/chunk/merge?fileId=${hash}&fileType=.mp4&totalChunks=${chunkCount}`)
        console.log("merge", res1)
        console.log('文件上传完成')
        return res1.data;
    } catch (error) {
        console.error('文件上传失败:', error)
        throw error
    }
    return null;
};

/**
 * 使用示例：
 * 
 * // 在Vue组件中使用
 * import { uploadBig } from '@/utils/uploadBig'
 * 
 * const handleFileUpload = async (file: File) => {
 *   try {
 *     await uploadBig(file, (progress) => {
 *       console.log(`上传进度: ${progress}%`)
 *       // 更新UI进度条
 *     })
 *     console.log('上传成功')
 *   } catch (error) {
 *     console.error('上传失败:', error)
 *   }
 * }
 * 
 * // 或者使用input元素
 * const fileInput = document.querySelector('input[type="file"]')
 * fileInput.addEventListener('change', (e) => {
 *   const file = e.target.files[0]
 *   if (file) {
 *     handleFileUpload(file)
 *   }
 * })
 */